#include "humidity.h"
#include "qumi_config.h"
#include "humidity_table.h"

volatile uint8_t g_humi = INVALID_HUMIDITY;

void Humidity_Init(void)
{
  /*  Init GPIO for humidity sensor*/
  /*GPIO_Init(HUMIDITY_PORT, HUMIDITY_PIN, GPIO_MODE_IN_FL_NO_IT);*/

  //Timer 1 Channel 3. 1KHz, 75% PWM
  /* Time Base configuration */
  TIM1_TimeBaseInit(TIM1_PRESCALER, TIM1_COUNTERMODE_UP, TIM1_PERIOD, 0);

  /* Channel 1, 2 and 3 Configuration in TIMING mode */  
  
  /* TIM3_Pulse = 750 */
  TIM1_OC1Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_ENABLE,
               TIM1_CH1_PERIOD, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_LOW, TIM1_OCIDLESTATE_RESET,
               TIM1_OCNIDLESTATE_RESET); 

  /*TIM1_ARRPreloadConfig(ENABLE);*/
  /*TIM1_OC3PreloadConfig(ENABLE);*/
  /*TIM1_ITConfig(TIM1_IT_UPDATE, ENABLE);*/
  /*TIM1_Cmd(ENABLE);*/
  /*[> Enable CC1 output<]*/
  /*TIM1_CtrlPWMOutputs(ENABLE);*/
}

void Humidity_Start(FunctionalState state)
{
  TIM1_CtrlPWMOutputs(state);
  TIM1_Cmd(state);
}

void Humidity_Task(void)
{
  uint16_t data = ADC1_GetBufferValue(HUMIDITY_CH);
  int8_t  temp = g_temp;
  uint8_t  i;
  uint16_t *tbl = 0;
  uint8_t  humi = 0;

  if ((temp >= 0) && (temp <= 50))
  {
    //valid temp. calc humidity
    tbl = g_humi_adc_tbl[temp/5].tbl;
    for (i=0; i<ADC_TBL_LEN; ++i)
    {
      if (data == *(tbl+i))
      {
        //find index
        humi = START_HUMIDITY + i*5;
        break;
      }
      else if (data < *(tbl+i))
      {
        humi = START_HUMIDITY + (i-1)*5;
        humi += 4 * (data - *(tbl+i-1)) / (*(tbl+i) - *(tbl+i-1));
        break;
      }
    }
    //TODO: humi validate
    if (humi == 0)
    {
      //humidity out of range
      g_humi = INVALID_HUMIDITY;
      return;
    }
    // calibrate
    /*if (temp % 5)*/
    {
      humi -= (temp % 5) / 2;
    }
    g_humi = humi - 10;
  }
  else
  {
    //invalid temp to calc humidity. set humidity to 0xFF
    g_humi = INVALID_HUMIDITY;
  }
}
